import store from '@/store'
import Request from './request'

import { REQUEST_BASE_URL } from '@/config'
Request.DEFAULT_BASE_URL = REQUEST_BASE_URL
const requestIntercept = {
  // 发出请求时的回调函数
  config (config) {
    uni.showLoading({
      title: '加载中',
      icon: 'loading',
      mask: true
    })
    console.log("e11111")
    try {
      const value = uni.getStorageSync('authorization');
      if (value) {
         console.log(value)
      }
    } catch (e) {
      // error
      console.log(e)
     
    }
    
    const token = store.state.user.token
    

    config = Object.assign({}, config, {
      url: `${config.url}`,
      header: {
        'content-type': 'application/x-www-form-urlencoded',
        'authorization': token
      },
      data: {
        ...config.data
      },
      method: config.method || 'POST'
    })
    console.log(`method:`,config.method, `data:` , config.data);
    return config
  },
  // 请求成功后的回调函数
  async success (response) {
    console.log(`response:`, response);
    uni.hideLoading()
    let errorMesg = ''
    // 可以在这里对收到的响应数据对象进行加工处理
    switch (response.statusCode) {
      case 200:
        let { code, msg } = response.data
        if (code != 1) {
          // 处理token过期、禁用、服务端redis异常问题
         if(code==24 || code === 403 ){
          uni.navigateTo({
            url: `/pagesA/auth/updataToken`
          });
          }else if( code === 500 || code === 21){
          

          } else {
            setTimeout(async () => {
              await uni.showToast({
                title: msg,
                icon: 'none',
                duration: 4000
              })
            }, 800);

          }
        }
        break
      case 500:
      case 502:
      case 503:
      case 504:
        errorMesg = '服务器出错'
        break
    }
    if (errorMesg.length > 0) {
      uni.showToast({
        title: errorMesg,
        icon: 'none'
      })
      throw new Error(errorMesg)
    }

    return response
  },
  fail (response) {
    uni.hideLoading()
    uni.showToast({
      title: '网络连接失败',
      icon: 'none'
    })
  }
}
export default new Request(requestIntercept)
